//
//  RowWKWebCell.m
//  
//  jhf
//
//  Created by 计海峰 on 2019/7/10.
//  Copyright © 2019 计海峰. All rights reserved.
//

#import "RowWKWebCell.h"
#import <CooperSDK/BaseWKWebviewVC.h>
#import <CooperSDK/CooperSDK.h>
#import <ReactiveObjC/ReactiveObjC.h>
#import "WKWebControlM.h"
#import "BindProtocol.h"

@interface RowWKWebCell () <WKUIDelegate, WKNavigationDelegate>

@end

@implementation RowWKWebCell

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self setup];
    }
    return self;
}

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        [self setup];
    }
    return self;
}

- (void)setup {
    [self.bgV addSubview:self.webView];
    [self.webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.bgV).insets(UIEdgeInsetsMake(0, 0, 0, 0));
        make.height.mas_equalTo(0).priorityLow();
    }];
}

- (void)bindTo:(__kindof id<BindProtocol>)model {
    [super bindTo:model];
    BindModel *bind = (BindModel *)model;
    WKWebControlM *info = (WKWebControlM *)bind.model;
    [info controlWebV:self.webView];
    // WKWebControlM *info = (WKWebControlM *)model;
//    if (info.url) {
//        [self.webView loadRequest:[NSURLRequest requestWithURL:cp_imageUrl(info.url)]];
//    }
//    if (info.htmlContent) {
//        [self.webView loadHTMLString:info.htmlContent baseURL:cp_imageUrl()];
//    }
    if (info.cellHeight > 0) {
        [self.webView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(info.cellHeight).priorityLow();
        }];
        if (bind.cellHeight != info.cellHeight + info.vBottomCons + info.vTopCons) {
            bind.cellHeight = info.cellHeight + info.vBottomCons + info.vTopCons;
            [bind.action runService:RefreshRowHeight any:bind.action.key];
        };
    }
//    self.webView.userInteractionEnabled = info.userInteractionEnabled;
}


#pragma mark getter
- (WKWebView *)webView{
    if (!_webView) {
        //创建WKWebview配置对象
        WKWebViewConfiguration*config = [[WKWebViewConfiguration alloc] init];
        // 偏好设置
        config.preferences = [[WKPreferences alloc] init];
        // 设置默认最小字体大小
        config.preferences.minimumFontSize = 10;
        // 不通过用户交互，是否可以打开窗口
        config.preferences.javaScriptCanOpenWindowsAutomatically = NO;
        config.mediaTypesRequiringUserActionForPlayback = WKAudiovisualMediaTypeNone;
        config.allowsInlineMediaPlayback = YES; //是否允许内联(YES)或使用本机全屏控制器(NO)，默认是NO。
        config.preferences.javaScriptEnabled = true;
        
        WKUserScript *noneSelectScript = nil;
        
        // js注入
        NSMutableString *javascript = [NSMutableString string];
        [javascript appendString:@"document.documentElement.style.webkitTouchCallout='none';"];//禁止长按
        [javascript appendString:@"document.documentElement.style.webkitUserSelect='none';"];//禁止选择
//        [javascript appendString:@"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);"];//图片自适应
        noneSelectScript = [[WKUserScript alloc] initWithSource:javascript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
        
        //创建webView
        WKWebView *webView = [[WKWebView alloc]initWithFrame:[UIScreen mainScreen].bounds configuration:config];
        [webView.configuration.userContentController addUserScript:noneSelectScript];
        
        //        [webView.configuration.userContentController addScriptMessageHandler:self name:@"getWkWebViewHeight"];
        
        // 代理
        webView.UIDelegate = self;
        webView.navigationDelegate = self;
        //        webView.scrollView.scrollEnabled = YES;
        
        @weakify(self)
        [[[[RACObserve(webView.scrollView, contentSize) distinctUntilChanged] throttle:0.2] filter:^BOOL(id  _Nullable value) {
            @strongify(self)
            CGSize p = [(NSValue *)value CGSizeValue];
            if (!self.model || p.height < 2) {
                return false;
            }
            return true;
        }] subscribeNext:^(id  _Nullable x) {
            @strongify(self)
            BindModel *bind = (BindModel *)self.model;
            WKWebControlM *model = (WKWebControlM *)bind.model;
//            DLog(@"value ----> %@", x);
//            DLog(@"cellHeight ----> %f", model.cellHeight);
            CGSize p = [(NSValue *)x CGSizeValue];
            if (fabs(model.cellHeight - p.height) < 2) {
                return ;
            }
            if (model.cellHeight > 0 && p.height > 0) { // 比例缩放
                CGFloat currentScale = (kScreen_Width - 24)/model.cellHeight;
                CGFloat targetScale = p.width / p.height;
                if ([[NSString stringWithFormat:@"%.1f", currentScale] isEqualToString:[NSString stringWithFormat:@"%.1f", targetScale]]) {
                    return;
                }
            }
            model.cellHeight = p.height;
//            if (p.width < kScreen_Width) {
                [bind.action runService:ReloadRow any:bind.action.key];
//            }
        }];
//        webView.userInteractionEnabled = false;
        _webView = webView;
    }
    return _webView;
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];
    
    // Configure the view for the selected state
}

@end
